package com.erp.serviceIMP;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.danga.MemCached.MemCachedClient;
import com.erp.dao.IndustryDAO;
import com.erp.entity.Industry;
import com.erp.exception.MyException;
import com.erp.service.IndustryService;


/**
 * 对Industry进行缓存层面的增删改查操作
 *
 * @author WangQian
 * @version 1.0.0
 */
@Service(value="industryService")
public class IndustryServiceIMP implements IndustryService {

    @Autowired
    private MemCachedClient memcachedClient;
    @Autowired
    private IndustryDAO industryMapper;
    
    private static final int maxRecord=9999;
    
    public MemCachedClient getMemcachedClient() {
        return memcachedClient;
    }

    public void setMemcachedClient(MemCachedClient memcachedClient) {
        this.memcachedClient = memcachedClient;
    }

    public IndustryDAO getIndustryMapper() {
        return industryMapper;
    }

    public void setIndustryMapper(IndustryDAO industryMapper) {
        this.industryMapper = industryMapper;
    }

    public List<Industry> findAll() {
        List<Industry> list = new ArrayList<Industry>();
        try {
            Industry industry = null;
            for (int i = 0; i < maxRecord; i++) {
                industry = (Industry) memcachedClient.get(keyStrategy(i));
                if (industry != null) {
                    list.add(industry);
                }
            }
            if (list.size() == 0) {
                list = industryMapper.findAll();
                for (Industry ind : list) {
                    memcachedClient.add(keyStrategy(ind.getId()), ind);
                }
            }
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return list;
    }

    public Industry findById(int id) {
        Industry industry = (Industry) memcachedClient.get(keyStrategy(id));
        if(industry==null){
            industry = industryMapper.findById(id);
            if(industry!=null){
                memcachedClient.add(keyStrategy(id), industry);
            }
        }
        return industry;
    }

    public void update(Industry industry) throws Exception {
        industryMapper.update(industry);
        memcachedClient.set(keyStrategy(industry.getId()), industry);
    }

    public int insert(Industry industry) throws Exception {
        industryMapper.insert(industry);
        int id=industry.getId();
        memcachedClient.set(keyStrategy(id), industry);
        return id;
    }

    public void delete(int id) throws Exception {
        industryMapper.delete(id);
        memcachedClient.delete(keyStrategy(id));
    }
    
    private String keyStrategy(int id){
        return "industry" + id;
    }

    
}
